<?php

class Model_Validate {
    /*
     * @method Validates if dates inputed are in the format "MM/YY" or "MM/YYYY"; and if the end date is BIGGER than the start date. 
     * @return boolean
     */

    public static function date_mmyy_pair($start_date, $end_date) {
        $sd = Model_Validate::extract_timestamp_from_mmyy($start_date);
        $ed = Model_Validate::extract_timestamp_from_mmyy($end_date);
        if (is_int($sd) && is_int($ed) && $sd <= $ed) {
            return true;
        }
        else
            return false;
    }

    public static function is_date_mmyy($date) {
        $date = explode("/", $date);
        if (count($date) > 2 || count($date) < 2 || !is_int($date[0]) || !is_int($date[1]) || $date[0] < 1 || $date[0] > 12 || (strlen($date[1]) != 2 && strlen($date[1]) != 4)) {
            return false;
        }
        else
            return true;
    }

    public static function extract_timestamp_from_mmyy($date) {
        if (Model_Validate::is_date_mmyy($date)) {
            $date = explode("/", $date);
            if (strlen($date[1]) == 2) {
                return strtotime("MM/yy");
            } else if (strlen($date[1]) == 4) {
                return strtotime("MM/YY");
            }
            else
                return false;
        }
        else
            return false;
    }

//        @return "ok" if everything is ok. Otherwise, returns an array of errors, with indexes such as: array[0] = array("field"=>"name", "msg"=>'message')
    public static function validate_signin_fields($fields) {
        $required_fields = array(
            "signin_name",
            "signin_email",
            "signin_email_confirm",
            "account_password",
            "account_password_confirm",
            "school_level",
            "institution_country",
            "institution_country_id",
            "institution_state",
            "institution_state_id",
            "institution_city",
            "institution_city_id",
            "institution",
            "institution_id",
            "institution_start",
            "institution_end",
        );
        $all_fields = array(
            "signin_name",
            "signin_email",
            "signin_email_confirm",
            "account_password",
            "account_password_confirm",
            "dob",
            "source",
            "gender",
            "school_level",
            "user_country",
            "user_country_id",
            "user_state",
            "user_state_id",
            "user_city",
            "user_city_id",
            "live_study_same_city",
            "institution_country",
            "institution_country_id",
            "institution_state",
            "institution_state_id",
            "institution_city",
            "institution_city_id",
            "institution",
            "institution_id",
            "institution_start",
            "institution_end",
            "classof",
            "classof_id"
        );
        $return = array();

//check for required fields
        foreach ($required_fields as $field) {
            if (!isset($fields[$field]) || $fields[$field] == "") {
                $return[] = array(
                    "field" => $field,
//                    "msg" => __("The field ':field' was required and has not been received", array(":field" => $field))
                    "msg" => __("O campo ':field' foi requerido, mas ele não foi recebido.", array(":field" => $field))
                );
            }
        }

        //only trim the fields for validation
        foreach ($all_fields as $field) {
            if (isset($fields[$field])) {
                $fields[$field] = trim($fields[$field]);
            }
        }
        //actually validate the fields one by one
        foreach ($all_fields as $field) {
            if (isset($fields[$field])) {
                switch ($field) {
                    case "signin_name":
                        if ($fields[$field] == "" || !is_string($fields[$field]) || strlen($fields[$field]) < 3) {
                            $return[] = array(
                                "field" => $field,
//                                "msg" => __("The field ':field' was required and has not been received", array(":field" => $field))
                                "msg" => __("O campo ':field' não possui um nome", array(":field" => $field))
                            );
                        }
                        break;
                    case "signin_email":
                    case "signin_email_confirm":

                        $regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/';
                        // Run the preg_match() function on regex against the email address
                        if (!preg_match($regex, $fields[$field])) {
                            $return[] = array(
                                "field" => $field,
//                                "msg" => __("The field ':field' was required and has not been received", array(":field" => $field))
                                "msg" => __("O campo ':field' não possui um email válido", array(":field" => $field))
                            );
                        }
                        if ($fields["signin_email"] !== $fields["signin_email_confirm"]) {
                            $return[] = array(
                                "field" => "signin_email",
//                                "msg" => __("The field ':field' was required and has not been received", array(":field" => $field))
                                "msg" => __("O campo 'Email' não é igual ao campo um email de 'Confirmação de Email'")
                            );
                            $return[] = array(
                                "field" => "signin_email_confirm",
//                                "msg" => __("The field ':field' was required and has not been received", array(":field" => $field))
                                "msg" => __("O campo 'Email' não é igual ao campo um email de 'Confirmação de Email'")
                            );
                        }
                        break;
                    case "account_password":
                    case "account_password_confirm":
                        if (!strlen($fields[$field]) < 5) {
                            $return[] = array(
                                "field" => $field,
                                "msg" => __("O campo ':field' não possui mais que 5 caracteres", array(":field" => $field))
                            );
                        }
                        if ($fields["account_password"] !== $fields["account_password_confirm"]) {
                            $return[] = array(
                                "field" => "account_password",
                                "msg" => __("O campo 'Senha' não é igual ao campo de 'Confirmação de Senha'")
                            );
                            $return[] = array(
                                "field" => "account_password_confirm",
                                "msg" => __("O campo 'Confirmação de Senha' não é igual ao campo de 'Senha'")
                            );
                        }
                        break;
                    case "dob":
                        //test for date like DD/MM/YYYY with years from 1930 to 2005
                        $regex = '/^[0-9]{1,2}\/[0-9]{1,2}\/(([0-9]{4})|([0-9]{2}))$/';
                        if ($fields[$field]!="" && !preg_match($regex, $fields[$field])) {
                            $return[] = array(
                                "field" => $field,
//                                "msg" => __("The field ':field' was required and has not been received", array(":field" => $field))
                                "msg" => __("O campo ':field' não possui um formato de data válido", array(":field" => $field))
                            );
                        } else if($fields[$field]!=""){
                            //make universal date format fields, check for impossible values (ie: month>12, etc)
                            list($day, $month, $year) = explode("/", $fields[$field]);
                            try {
                                $datetime = new DateTime("$year-$month-$day");
                            } catch (Exception $e) {
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui um formato de data válido", array(":field" => $field))
                                );
                            }
                            
                            //check range of fields
                            $strtotime = strtotime($datetime->format("Y-m-d"));
                            if($strtotime <  strtotime("1930-01-01") || $strtotime >  strtotime("2004-01-01")){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui uma data válida (entre 1930 e 2004)", array(":field" => $field))
                                );
                            }
                        }
                        break;
                    case "source":
                        if(intval($fields[$field])<0  || intval($fields[$field])>4){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui um valor aceito", array(":field" => $field))
                                );
                        }
                        break;
                    case "gender":
                        if(intval($fields[$field])!=0  && $fields[$field]!=="male" && $fields[$field]!=="female"  ){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui um valor aceito", array(":field" => $field))
                                );
                        }
                        break;
                    case "school_level":
                        if(intval($fields[$field])<0  || intval($fields[$field])>6){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui um valor aceito", array(":field" => $field))
                                );
                        }
                        break;
                        
                    case "institution_country":
                    case "user_country":
                        $type="";
                        if($field=="institution_country"){
                            $type="institution";
                        } else{
                            $type = "user";
                        }
                        
                        if($fields[$field] !== ""){
                            $country = Model_Country::search_country($fields[$field]);
                             if(sizeof($country)!=1 || $country[0]["id"] != $fields[$type."_country_id"]){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui um país escolhido corretamente", array(":field" => $field))
                                );
                             }
                        }
                        break;
                        
                    case "institution_country_id":
                    case "user_country_id":
                        $type="";
                        if($field=="institution_country_id"){
                            $type="institution";
                        } else{
                            $type = "user";
                        }
                        
                        if($fields[$field] !== ""){
                            $country = new Model_Country($fields[$field]);
                             if($country->get_name() != $fields[$type."_country"]){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui um país escolhido corretamente", array(":field" => $field))
                                );
                             }
                        }
                        break;
                    case "user_state":
                    case "institution_state":
                         $type="";
                        if($field=="institution_state"){
                            $type="institution";
                        } else{
                            $type = "user";
                        }
                        if($fields[$field] !== ""){
                            $state = Model_State::search_state($fields[$field]);
                             if(sizeof($state)!=1 || $state[0]["id"] != $state[$type."_state_id"]){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui um país escolhido corretamente", array(":field" => $field))
                                );
                             }
                        }
                        break;
                    case "user_state_id":
                    case "institution_state_id":
                        $type="";
                        if($field=="institution_state_id"){
                            $type="institution";
                        } else{
                            $type = "user";
                        }
                        if($fields[$field] !== ""){
                            $state = new Model_State($fields[$field]);
                             if($state->get_name() != $fields[$type."_state"] || $state->get_country() != $fields[$type."_country_id"]){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui um estado escolhido corretamente", array(":field" => $field))
                                );
                             }
                        }
                        break;
                    case "user_city":
                    case "institution_city":
                        $type="";
                        if($field=="institution_city"){
                            $type="institution";
                        } else{
                            $type = "user";
                        }
                        if($fields[$field] !== ""){
                            $city = Model_City::search_city($fields[$field]);
                             if(sizeof($city)!=1 || $city[0]["id"] != $city[$type."_city_id"] ){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui uma cidade escolhido corretamente", array(":field" => $field))
                                );
                             }
                        }
                        break;
                    case "user_city_id":
                    case "institution_city_id":
                        $type="";
                        if($field=="institution_city_id"){
                            $type="institution";
                        } else{
                            $type = "user";
                        }
                        if($fields[$field] !== ""){
                            $city = new Model_City($fields[$field]);
                             if($city->get_name() != $fields[$type."_city"] || $city->get_state() != $fields[$type."_state_id"]){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui uma cidade escolhida corretamente", array(":field" => $field))
                                );
                             }
                        }
                        break;
                    case "live_study_same_city":
                        //NOTICE: $fields["live_study_same_city"] will only be set if the checkbox is marked, so there is no need to check it's value
                        if($fields["user_country"] !== $fields["institution_country"] || $fields["user_country_id"] !== $fields["institution_country_id"] || $fields["user_state"] !== $fields["institution_state"] || $fields["user_state_id"] !== $fields["institution_state_id"] || $fields["user_city"] !== $fields["institution_city"] || $fields["user_city_id"] !== $fields["institution_city_id"]){
                            $return[] = array(
                                "field" => $field,
                                "msg" => __("O campo ':field' foi marcado, mas nem todos os dados do local do usuário e da sua instituição de ensino são iguais", array(":field" => $field))
                            );
                            
                        }
                        break;
                    case "institution":
                        if($fields[$field] !== ""){
                            $city = Model_City::search_city($fields[$field]);
                             if(sizeof($city)!=1 || $city[0]["id"] != $city[$type."_city_id"] ){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui uma cidade escolhido corretamente", array(":field" => $field))
                                );
                             }
                        }else{
                            $return[] = array(
                                "field" => $field,
                                "msg" => __("O campo ':field' está vazio", array(":field" => $field))
                            );
                            
                        }
                        break;
                    case "institution_id":
                        if($fields[$field] !== ""){
                            $institution = new Model_Institution($fields[$field]);
                             if($institution->get_name() != $fields["institution"] || $institution->get_city() != $fields["institution_city_id"]){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' se refere a uma instituição de outra cidade", array(":field" => $field))
                                );
                             }
                        }
                        break;
                    case "institution_start":
                    case "institution_end":
                        if($fields[$field] !== "" && !Model_Validate::date_mmyy_pair($fields["institution_start"], $fields["institution_end"])){
                            $return[] = array(
                                "field" => $field,
                                "msg" => __("O campo ':field' não faz um par válido de início/fim de data no format MM/YY", array(":field" => $field))
                            );
                        }
                        break;
                    case "class_of":
                        if($fields[$field] !== ""){
                            $classof = Model_Classof::search_classof($fields[$field]);
                             if(sizeof($classof)!=1 || $classof[0]["id"] != $classof["classof_id"] ){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' não possui uma classe escolhida corretamente", array(":field" => $field))
                                );
                             }
                        }else{
                            $return[] = array(
                                "field" => $field,
                                "msg" => __("O campo ':field' está vazio", array(":field" => $field))
                            );
                        }
                        break;
                    case "classof_id":
                        if($fields[$field] !== ""){
                            $classof = new Model_Classof($fields[$field]);
                             if($classof->get_name() != $fields["classof"] || $classof->get_institution() != $fields["institution_id"]){
                                $return[] = array(
                                    "field" => $field,
                                    "msg" => __("O campo ':field' se refere a uma class de outra instituição", array(":field" => $field))
                                );
                             }
                        }
                        break;
                }
            }
        }

        //check if any error occured after all validations
        if (count($return) == 0)
            return true;
        else
            return $return;
    }

}